<script setup>
import { ref,reactive, nextTick,onActivated,getCurrentInstance,onMounted, watch,onDeactivated  } from 'vue'; 
import { useRoute,useRouter } from 'vue-router';
import { ElMessage,ElMessageBox  } from 'element-plus';
import { merchantManagementList, resetUserPassword } from '@/api/BussinessMenage/index.js';
import { useDistInfoStore } from '@/stores/dict.js'
import { useglobalStore } from '@/stores/global.js'
// import { getDistInfo } from '@/api/Other/index.js'
const seachTable = ref(null);
const route = useRoute();
const router = useRouter();
const distInfoStore = useDistInfoStore();
const globalStore = useglobalStore();
const instance = getCurrentInstance();

let timer = null
// 新增编辑回退时候刷新列表
onActivated(async()=>{
    let closeTagName = sessionStorage.getItem('closeTagName');
    console.log(closeTagName,'closeTagName');
    if(closeTagName == 'MerchantChildManageEdit'){
        seachTable.value.handlerSearch();
      
    }else if(closeTagName == 'MerchantChildManageAdd' || closeTagName == 'MerchantChildManageStoreAdd'){
        seachTable.value.initSearch();
    }else if(globalStore.merchantId?.length > 0){
      filterStore(merchantGroupingData,3,globalStore.merchantId)
      timer = setTimeout(() => {
        seachTable.value.initSearch();
      },100)
    }else{
      seachTable.value.initSearch();
    }
    instance.proxy.$forceUpdate();
    sessionStorage.removeItem('closeTagName');
})

// onDeactivated(() => {
//   console.log('onDeactivated');
//   globalStore.setAllClear()
// })

const filterStore = (oldDta,index,comparativeData) => {
// console.log(oldDta,'comparativeData');

let result = comparativeData.length === 0 ? [] : oldDta?.value.filter(item => comparativeData.includes(item.value))
formInline.value[index].data = merchantGroupingData.value
formInline.value[index].model = result.map(v => {
  return v.value
})

}


onBeforeUnmount(() => {
  clearTimeout(timer)
  timer = null
  globalStore.merchantId = []
})


// 商户分组数据
const merchantGroupingData = computed(()=>{
    return distInfoStore.getDistInfos("商户分组").map(lis=>{
        return {
            value:lis.id,
            label:lis.permissionName
        }
    })
})

//门店分组列表 
// const storeList = computed(()=>{
//     return distInfoStore.getDistInfo("门店分组").map(lis=>{
//         return {
//             value:lis.id,
//             label:lis.permissionName
//         }
//     })
// })

// 跳转到门店逻辑
const goDoorManege = (row) => {
  globalStore.setAllClear()
  globalStore.setBusiness(row.name)
  router.push({name:'StoreManageIndex'})
}
const formInline = ref([
    {
      type: "datePicker",
      prop: ["beginTime", "endTime"],
      startPlaceholder: "创建开始时间",
      endPlaceholder: "创建结束时间",
      label: "",
      model: [],
    },
    {
      type: "input",
      prop: "keywords",
      placeholder: "商户名称/ID",
      label: "",
      model: "",
    },
    {
      type: "input",
      prop: "address",
      placeholder: "所属地区",
      label: "",
      model: "",
    },
    // {
    //     type: "cascader",
    //     prop: "areaCode",
    //     placeholder: "所属地区",
    //     label: "",
    //     state: "default",
    //     model: "",
    //     data: newArea(),
    //     props: {
    //         label: "name",
    //         value: "code",
    //         children: "children",
    //     }
    // },
    {
        type: "select",
        placeholder: "商户分组",
        label: '',
        multiple:true,
        prop: 'busiGroupIds',
        handleChange:(val) => {
          globalStore.merchantId = val
        },
        data:merchantGroupingData.value,
        model:(() => {
            let value = merchantGroupingData.value
            if(value.length == 1){
              console.log(value,'value');
                return [value[0].value]
            }else{
                return []
            }
        })()
    },
    {
        type: "select",
        placeholder: "经营方式",
        label: '',
        prop: 'busiWays',
        multiple:true,
        data:[
            {
                label:"直营",
                value:1
            },
            {
              
                label:"加盟",
                value:2
            }
        ],
        model: []
    },
])

const btnLefts = ref([
    {
        label:"新增",
        plain:false,
        type:"primary",
        show:true,
        img:new URL("@/assets/icon/btn-add.png",import.meta.url),
        click:async ()=>{
            router.push({name:"MerchantChildManageAdd"})
        }
    },

])
const btnRights = ref([
    // {
    //     label:"导出",
    //     plain:false,
    //     plain:true,
    //     show:true,
    //     img:new URL("@/assets/icon/btn-export.png",import.meta.url),
    //     style:"border-color:#0C268C;color:#0C268C",
    //     click:async ()=>{

    //     }
    // }
])

const tableConfig = ref([
    {
      prop: "code",
      label: "商户ID",
      width:200
    },
    {
      prop: "name",
      label: "商户名称",
      width:200
    },
    {
      prop: "addr",
      label: "所属地区",
      width:200
    },
    {
      prop: "busiGroupId",
      label: "商户分组",
      width:200,
      format:(val) => {
        if(val){
          let newArray = val.split(',')
          let matches = []
          for (const valueToMatch of newArray) {
              const matchingItem = merchantGroupingData.value.find(item => item.value === valueToMatch);
              if (matchingItem) { 
                  matches.push(matchingItem.label);
              }
            }
          return matches.join(",");
        }else{
          return '-'
        }
      }
    },
    {
      prop: "busiWay",
      label: "经营方式",
      width:200,
      format:(value,row) => {
        if(value == 1){
          return '直营'
        }else{
          return '加盟'
        }
      }
    },
    {
      prop: "linkman",
      label: "联系人",
      width:200
    },
    {
      prop: "phone",
      label: "账号",
      width:200
    },
    {
      prop: "remark",
      label: "备注",
      width:200
    },
    {
      // type:'slot',
      // slotName:'doorNumber',
      prop: "storeCount",
      label: "门店数量",
      width:200
    },
    {
      type:'slot',
      slotName:'storeList',
      slotHeaderName:'manageTheNumberOfStores',
      needHeader:true,
      prop: "canViewCount",
      label: "管理门店数",
      width:200
    },
    {
      prop: "creator",
      label: "创建人",
      width:200
    },
    {
      prop: "createTime",
      label: "创建时间",
      width:200
    },
    {
      type: "action",
      label: "操作",
      width: 350,
      btns: [
        {
          label: () => "编辑",
          type:"success",
          show:(row)=>{
            return true;
          },
          click: async (row) => {

            router.push({name:"MerchantChildManageEdit",query:{id:row.id}})
          },
        },
        {
          label: () => "重置密码",
          type:"primary",
          show:(row)=>{
            return true;
          },
          click: async (row) => {

            ElMessageBox.confirm(`是否将密码重置为Aa+商户联系人手机号后6位+！`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
              beforeClose: async (action, instance, done) => {
                if (action === 'confirm') {
                  try{
                    tableLoading.value = true
                    instance.confirmButtonLoading = true;
                    instance.confirmButtonText = '执行中...';
                    console.log(row,'row');
                    let params = {
                      id:row.id
                    }
                    
                    const result = await resetUserPassword(params)
                    // console.log(result,'result');
                    instance.confirmButtonLoading = false;
                    
                    ElMessage({
                      type: 'success',
                      message: '重置成功!' 
                    });
                    seachTable.value.handlerSearch();
                  }finally{
                    tableLoading.value = false
                    done()
                  }
                 
                } else {
                  done()
                }
              }
            })
          },
        },
        {
          label: () => "新增门店",
          type:"primary",
          show:(row)=>{
            return true;
          },
          click: async (row) => {

            router.push({name:"MerchantChildManageStoreAdd",query:{id:row.id,storeGroupId:row.storeGroupId,name:row.name}})
          },
        },
      ],
    },
]);
const tableLoading = ref(false)
const totalPage = ref(0)
const tableData = ref([]);


const handlerSearch = async (formInline)=>{
    tableLoading.value = true;
    try{
      console.log(formInline,'formInline');
        let data = {
          ...formInline,
        }
        console.log(data);
        const res = await merchantManagementList(data)
        totalPage.value = Number(res.total)
        tableData.value = res.records
    }catch(e){
       
    }finally{
        tableLoading.value = false;
    }
}



</script>
<template>
    <div class="page-content">
        <SeachTable 
          :tableType="1"
          ref="seachTable"
          :forms="formInline"
          :btnLefts="btnLefts"
          :btnRights="btnRights"
          :tableLoading="tableLoading"
          :tableConfig="tableConfig"
          :tableData="tableData"
          :noResetTable="true"
          :totalPage="totalPage"
          @handlerSearch="handlerSearch"
        >
        <template #storeList="{row}">
            <div v-if="row.canViewCount" class="door-number" @click="goDoorManege(row)">
                {{row.canViewCount}}
              </div>
              <div v-else>-</div>
        </template>

         <template #manageTheNumberOfStores>
          <div class="tips-tool-box">
            管理门店数
          <el-tooltip placement="top">
              <template #content>
                  <div class="tips-info">
                     当前操作账号有权限管理的门店数量
                  </div>
              </template>
              <img src="@/assets/images/warning-circle.png" alt="" class="img">
          </el-tooltip>
          </div>
          

        </template>
        </SeachTable>
    </div>
</template>


<style lang="less" scoped>
  .door-number{
    cursor: pointer;
    color: #3480FF;
  }
  .img{
        margin-left: 4px;
        width: 14px;
        height: 14px;
        cursor: pointer;
    }
    .tips-tool-box{
      display: flex;
      align-items: center;
    }
</style>
